package accounts;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class CreateAccountServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws IOException {
		
		Key accountKey = KeyFactory.createKey("Accounts", "accountName");
		// requests for the user name and password given by new user
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String firstName = req.getParameter("firstName");
		String lastName = req.getParameter("lastName");
		String userRole = req.getParameter("userRole");
		
		// creates an entity account
		Entity account = createEntity(accountKey, username, password, firstName, lastName,userRole);
		// adds the created entity to the datastore
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(account);
		// redirects to a confirmation page
		resp.sendRedirect("/loginsuccess.jsp?&username="+username);
	}
	
	/* 
	 * Pre: the chosen user name and password has been entered by the new user
	 * Post: creates an entity with the given parameters
	 */
	public static Entity createEntity(Key key, String username, String password,  String fName, String lName, String uRole) {
		Entity account = new Entity("Account", key);
		//String accout_type = "user";
		//String accout_type = "admin";
		account.setProperty("username", username);
		account.setProperty("password", password);
		account.setProperty("firstName", fName);
		account.setProperty("lastName", lName);
		account.setProperty("account_type", uRole);
		account.setProperty("lockStatus","Unlocked");
		return account;
	}
}
